package com.itheima.skyserver.interceptor;

import com.itheima.skyserver.context.BaseContext;
import com.itheima.skyserver.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            log.info("LoginInterceptor 拦截请求，没有令牌，直接封装未授权响应结果!");
            response.setStatus(401);
            return false;
        }
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Long empId = Long.valueOf(claims.get("id").toString());
            BaseContext.setCurrentId(empId);
        } catch (Exception e) {
            log.info("LoginInterceptor 拦截请求：令牌无效，直接封装未授权响应结果");
            response.setStatus(401);
            return false;
        }
        log.info("LoginInterceptor 拦截请求：令牌有效，直接放行");
        return true;
    }
}
